// manager/pages/gridtask/index.js
import config from '../../../utils/config';
import { getSystemInfo } from '../../../utils/getSystemInfo';
import { request } from '../../../utils/request';
import util from '../../../common/util';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isPerson: config.isPerson,
        activeIndex: 0,
        tabList: [
            {
				id: 1,
                text: "拜访任务"
            },
            {
				id: 2,
                text: "预约任务"
            }
        ],
        showFilter: false,
        params: {
            search: "",
            phone: "",
            // 1-个人，2-商户，3-企业，4-新型农业主体
            merchantType: 2,
        },
        // 客户字典
        typeList: [],
        typeIndex: 0,
        scroller: {
			pageNum: 0,
			pageSize: 10,
			totalPage: 10,
			isNoneLoading: true,
			refreshColor: '#000000',
			refreshDiy: false,
			isloaded: false,
			list: []
        },
        currentIndex: 0,
        show: false,
        actions: [],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getDictionaryInfo();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
		
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 页面加载时执行一次加载
        this.resetScroller()
        this.listData()
    },

    resetScroller(){
        let scroller = {
			pageNum: 0,
			pageSize: 10,
			totalPage: 10,
			isNoneLoading: true,
			refreshColor: '#000000',
			refreshDiy: false,
			isloaded: false,
			list: []
		}
		this.setData({
			scroller
		})
    },

    /**
     * 验证params是否有值
     */
    validateParams(){
        let isFilter = false;
        let { params } = this.data;
        for(let key in params){
            if(['merchantType'].indexOf(key) == -1 && params[key]){
                isFilter = true;
            }
        }
        this.setData({
            isFilter
		})
    },
    /**
     * 重置参数
     */
    resetParams(){
        let { params, typeList } = this.data;
        Object.keys(params).forEach(key => {
            if(key != "merchantType"){
                params[key] = ''
            }else{
                params[key] = 2
            }
        })
        // 默认商户
        let typeIndex = typeList.findIndex(item => item.dictValue == 2)
		this.setData({
            params,
            typeIndex,
            isFilter: false
		})
    },

    tabChange(e){
        let { index } = e.currentTarget.dataset;
        this.setData({
            activeIndex: index
        })
        this.resetParams();
		this.resetScroller();
		this.listData();
    },
    /**
     * 获取字典
     */
    getDictionaryInfo() {
        request({
            url: "/commonApi/getDictionaryInfo",
            method: "GET",
            data: {
				dictType: "ecard_cust_type"
			}
        }).then(res => {
            if(res.code == 0){
                let typeList = [];
                // 是否显示个人
                if(this.data.isPerson){
                    typeList = res.data;
                }else{
                    res.data.forEach(item => {
                        if(item.dictValue != 1){
                            typeList.push(item)
                        }
                    })
                }
                // 默认商户
                let typeIndex = typeList.findIndex(item => item.dictValue == 2)
                this.setData({
                    typeList,
                    typeIndex
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 显示筛选
     */
    showFilterPopup(){
        this.setData({
            showFilter: true
        })
    },
    /**
     * 关闭筛选
     */
    closeFilter(){
        this.setData({
            showFilter: false
        })
    },
    /**
     * 确认筛选
     */
    confirmFilter(){
        this.setData({
            showFilter: false
        })
        this.validateParams();
        this.resetScroller();
        this.listData();
    },
    /**
     * 输入框输入时
     */
    input(e){
        console.log(e)
        let key = e.target.dataset.key;
        this.setData({
            ['params.'+key]: e.detail.value,
        })
    },
    bindPickerChange(e){
        this.setData({
            typeIndex: e.detail.value,
        })
    },
    // 搜索
    searchConfirm(e){
        console.log(e)
        let key = e.currentTarget.dataset.key;
        this.setData({
            ['params.'+key]: e.detail.value,
            showFilter: false
        })
        // 页面加载时执行一次加载
		this.resetScroller()
		this.listData()
    },
    searchBtn(e){
        this.setData({
            'params.merchantType': this.data.typeList[this.data.typeIndex].dictValue
        })
        this.resetScroller()
		this.listData()
    },

    /**
     * 获取网格任务列表
     */
    listData: function () {
		let { scroller } = this.data;
        scroller.pageNum = scroller.pageNum + 1;
        if(scroller.pageNum>scroller.totalPage){
            return
        }
        request({
            url: this.data.activeIndex == 0 ? `/merchantMarketing/getMerchantTaskList` : `/merchantMarketing/getMerchantReservationTaskList`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                pageNum: this.data.scroller.pageNum,
                pageSize: this.data.scroller.pageSize,
                ...this.data.params
            }
        }).then(res => {
            if(res.code == 0){
                scroller.totalPage = Math.ceil(res.total/scroller.pageSize);
                if(scroller.pageNum>=scroller.totalPage){
                    scroller.isNoneLoading = false;
                }
                if(res.data.length>0){
                    res.data.map(item => {
                        item.creationTime = item.creationTime?util.formatTime(new Date(item.creationTime)):"";
                        item.endDate = item.creationTime?util.formatDate(new Date(item.endDate)):"";
                        item.appointmentDate = item.appointmentDate?util.formatDate(new Date(item.appointmentDate)):"";
                        return item
                    })
                }
                if(scroller.pageNum == 1){
                    scroller.list = res.data;
                }else{
                    scroller.list = scroller.list.concat(res.data);
                }
                console.log(res.data,scroller.list)
                this.setData({
                    scroller
                })
            }
        }).catch(error => {
            // console.log(error)
        })	
    },
    
	refresh: function () {
        this.resetScroller()
		this.listData()
    },
    
	loadMore: function () {
		this.listData()
    },

    /**
     * 拨打电话
     */
    makePhoneCall(e) {
        let { tel,index } = e.currentTarget.dataset;
        if(!tel){
            wx.showToast({
                title: "暂无联系方式",
                icon: 'none',
                duration: 2000
            })
            return
        }
        getSystemInfo({
            android: () => {
                let actions = [
                    { name: tel, color: '#999', disabled: true },
                    { name: '呼叫', color: '#000' },
                ]
                this.setData({
                    show: true,
                    currentIndex: index,
                    actions
                })
            },
            ios: () => {
                wx.makePhoneCall({
                    phoneNumber: tel
                })
            }
        })
    },

    /**
     * 复制电话
     */
    copy(e){
        let { tel } = e.currentTarget.dataset;
        wx.setClipboardData({
            data: tel,
            success (res) {
                wx.hideToast()
                wx.showToast({
                    title: "电话已复制",
                    icon: 'none',
                    duration: 2000
                });
            }
        })
    },
    /** 跳转商户详情 */
    toMerchantdesc(e) {
        let { item } = e.currentTarget.dataset;
        wx.navigateTo({
          url: `/manager/pages/merchantdesc/index?merchantId=${item.merchantId}`,
        })
    },
    /** 跳转企业详情 */
    toEnterprisedesc(e) {
        let { item } = e.currentTarget.dataset;
        wx.navigateTo({
          url: `/manager/pages/enterprisedesc/index?enterpriseId=${item.merchantId}`,
        })
    },
    /** 导航 */
    navigateTo(e) {
        // console.log(e.currentTarget.dataset)
        let { item } = e.currentTarget.dataset;
        if(!item.coordinate){
            wx.showToast({
                title: "暂无位置信息",
                icon: 'none',
                duration: 2000
            })
            return
        }
        let arr = item.coordinate.split(",")
        wx.openLocation({
            name: item.mapAddress,
            latitude: Number(arr[0]),
            longitude: Number(arr[1])
        })
    },
	/**
     * 执行任务
     */
    toExecute(e){
        let { merchantid, id} = e.currentTarget.dataset;
        if(this.data.activeIndex == 0){
            wx.navigateTo({
                url: `/manager/pages/addvisit/index?merchantId=${merchantid}&merchantType=${this.data.params.merchantType}`,
            })
        }else{
            wx.navigateTo({
                url: `/manager/pages/makappointment/index?merchantId=${merchantid}&id=${id}&merchantType=${this.data.params.merchantType}`,
            })
        }
    },
    onSelect(e) {
        console.log(e)
        this.setData({
            show: false
        })
        wx.makePhoneCall({
            phoneNumber: this.data.scroller.list[this.data.currentIndex].telNo
        })
    },
    onCancel() {
        this.setData({ show: false });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    }
})